package com.cmol.peopledetectapp;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.cmol.data.GlobalData;
import com.cmol.data.Host;
import com.cmol.peopledetectapp.admin.AdminLogActivity;
import com.cmol.peopledetectapp.user.FaceRecognitionActivity;
import com.cmol.peopledetectapp.user.MapActivity;
import com.cmol.peopledetectapp.user.RegisterActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.Proxy;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * app主界面
 * 登录注册
 *
 * @author 邢文成
 */
public class MainActivity extends AppCompatActivity {
    /**
     * 账号
     */
    private EditText account;
    /**
     * 密码
     */
    private EditText password;

    /**
     * 判断返回时连按两次时间
     */
    private long exitTime;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        GlobalData.setUserToken("");
        setContentView(R.layout.activity_main);
        account = findViewById(R.id.editText2);
        password = findViewById(R.id.editText);


        Log.e("=============================================", "onCreate: main创建\n\n\n\n\n\n\n");

    }

    /**
     * 用户注册
     *
     * @param view 当前布局
     */
    public void UserRegisterClick(View view) {
        startActivity(new Intent(this, RegisterActivity.class));
    }

    /**
     * 隐藏的管理员登录
     *
     * @param view 布局
     */
    public void EnterAdministerClick(View view) {
        Log.e("=============================================", "\n\n\n\n\n\n\n");
        startActivity(new Intent(this, AdminLogActivity.class));
    }

    /**
     * 使用账号密码登录
     *
     * @param view 布局
     */
    public void PasswordLogClick(View view) {
        GlobalData.setCurrentEmail(account.getText().toString());
        askForLogin(account.getText().toString(), password.getText().toString());
        Intent intent = new Intent(MainActivity.this, MapActivity.class);

//        // 测试界面
//        Intent intent = new Intent(MainActivity.this, MapActivity.class);
//        startActivity(intent);
//        finish();
    }

    /**
     * 登录主方法
     *
     * @param account  账号
     * @param password 密码
     */
    private void askForLogin(String account, String password) {
        String patternAccount = "^0?[A-Z a-z 0-9]+@[A-Z a-z 0-9]+\\.com";
        String patternPassword = "^[A-Z a-z 0-9]+";
        Log.e("===================", String.valueOf(account.matches(patternAccount) && password.matches(patternPassword)));
        if (account.matches(patternAccount) && password.matches(patternPassword)) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this, "登录中", Toast.LENGTH_SHORT).show();
                }
            });
            /*
             * 通信等待参数
             */
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(10, TimeUnit.SECONDS)
                    .readTimeout(10, TimeUnit.SECONDS)
                    .writeTimeout(10, TimeUnit.SECONDS)
                    .proxy(Proxy.NO_PROXY)
                    .build();
            /*
             * 请求报文体json
             */
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("account", account);
                jsonObject.put("password", password);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
            RequestBody requestBody = RequestBody.create(mediaType, "" + jsonObject.toString());
            /*
             * 请求报文
             */
            Request request = new Request.Builder()
                    .url(Host.host + "/user/login")
//                .addHeader("Authorization", GlobalData.getUserToken())
                    .post(requestBody)
                    .build();
            Log.e("requestBody", requestBody.toString());
            Call call = okHttpClient.newCall(request);
            /*
             * 异步响应
             */
            call.enqueue(new Callback() {
                /**
                 * Called when the request could not be executed due to cancellation, a connectivity problem or
                 * timeout. Because networks can fail during an exchange, it is possible that the remote server
                 * accepted the request before the failure.
                 *
                 * @param call
                 * @param e
                 */
                @Override
                public void onFailure(Call call, IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.e("==============body:", e.toString());
                            Toast.makeText(MainActivity.this, "网络请求异常", Toast.LENGTH_SHORT).show();
                        }
                    });
                }


                /**
                 * Called when the HTTP response was successfully returned by the remote server. The callback may
                 * proceed to read the response body with . The response is still live until
                 * its response body is {@linkplain ResponseBody closed}. The recipient of the callback may
                 * consume the response body on another thread.
                 *
                 * <p>Note that transport-layer success (receiving a HTTP response code, headers and body) does
                 * not necessarily indicate application-layer success: {@code response} may still indicate an
                 * unhappy HTTP response code like 404 or 500.
                 *
                 * @param call
                 * @param response
                 */
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    final String res = Objects.requireNonNull(response.body()).string().trim();
//                Log.e("=====================res",response.toString());
                    Log.e("====body: ", res);
                    if (response.code() == 200) {
                        try {
                            JSONObject json = new JSONObject(res);
                            /**
                             * token:
                             * boolean auth:
                             */
                            boolean auth = false;
                            auth = json.getBoolean("auth");

                            if (auth) {
                                String token = json.getString("token");
                                GlobalData.setUserToken(token);
                                Log.e("auth==============================", String.valueOf(auth));
                                Intent intent = new Intent(MainActivity.this, MapActivity.class);
                                startActivity(intent);
                                finish();
                            } else {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(MainActivity.this, "验证失败", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, "服务器异常" + response.code(), Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                }
            });
        } else {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Log.e("=========================失败提示", "================================================sadffffffff");
                    Toast.makeText(MainActivity.this, "请输入正确格式账号或者密码", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    /**
     * 人脸识别登录
     *
     * @param view
     */
    public void FaceLogClick(View view) {
        Intent intent = new Intent(this, FaceRecognitionActivity.class);
        // 传递调用类型：登录
        intent.putExtra("type", "0");
        startActivity(intent);
        finish();
    }

    /**
     * 按两次才退出
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}

